package ug.co.icom.kyazze.healthticket.images;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import ug.co.icom.kyazze.healthticket.services.ApplicationObject;
import android.app.IntentService;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

/**
 * Intent Service that uploads a user's profile picture to a remote server
 * 
 * @author KYAZZE MICHAEL
 * 
 */
@SuppressWarnings("deprecation")
public class IntentProfileImageService extends IntentService {
	private final static String TAG = "IntentProfileImageService";
	private String webAddressToPost = "http://appitconsult.com/healthticket/image_upload.php";
	private Bitmap bitmap;
	File directory;
	private String filepath = "healthTicket_files";
	long numb;

	public IntentProfileImageService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		//receivedChoice = extras.getLong("choice");
		//Bundle extras = getIntent().getExtras();
//		
//		Bundle extras = intent.getExtras();
//		   if (extras != null) 
//		   {
//		     numb = Long.parseLong(extras.getString("Pnumber"));
//		   }
//		
//		ApplicationObject obj = new ApplicationObject();
		ApplicationObject obj = (ApplicationObject)getApplicationContext();
		numb = obj.getphone_number();
		
//		if(intent.hasExtra("byteArray")) {
//		    bitmap = BitmapFactory.decodeByteArray(
//		        intent.getByteArrayExtra("byteArray"),0,intent.getByteArrayExtra("byteArray").length);        
//		}

		bitmap = BitmapFactory.decodeByteArray(
				intent.getByteArrayExtra("byteArray"), 0,
				intent.getByteArrayExtra("byteArray").length);

		ContextWrapper contextWrapper = new ContextWrapper(
				getApplicationContext());
		directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);

		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost postRequest = new HttpPost(webAddressToPost);
			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.JPEG, 100, bos);
			byte[] data = bos.toByteArray();
			entity.addPart("uploaded", new ByteArrayBody(data, numb + ".jpg")); // ImageName
			postRequest.setEntity(entity);
			HttpResponse response = httpClient.execute(postRequest,
					localContext);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse;
			StringBuilder s = new StringBuilder();

			while ((sResponse = reader.readLine()) != null) {
				s = s.append(sResponse);
			}
			System.out.println("Response: " + s);

			filesave(data);
		} catch (Exception e) {
			e.getMessage();
		}
	}

	// TODO insert picture uri into profile folder table and mongodb document

	String inputfile = directory + "/" + numb + ".jpg";

	private void filesave(byte[] file) throws IOException {

		FileOutputStream fileOutput = new FileOutputStream(directory + "/"
				+ numb + ".jpg");

		fileOutput.write(file);
		// close the output stream when done
		fileOutput.close();

	}

}
